import java.util.ArrayList;
import java.util.Arrays;

public class MyArrayList {
    private int[] elem;
    private int usedSize;
    private static final int DEFAULT_SIZE = 5;

    public MyArrayList() {
        //构造方法
        this.elem = new int[DEFAULT_SIZE];
    }

    public MyArrayList(int initCapacity) {
        //自定义容量的构造方法
        this.elem = new int[initCapacity];
    }


    public void display() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    public boolean isFull() {
        return this.usedSize == this.elem.length;
    }

    public void add(int data) {
        // 新增元素,默认在数组最后新增
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);
        }
        this.elem[this.usedSize++] = data;
    }

    public void add(int pos, int data) {

        // 在 pos 位置新增元素
        if (pos < 0 || pos > this.usedSize) {
            throw new PosOutOfBoundsException(pos + "位置不合法！");
        }
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);
        }
        for (int i = this.usedSize - 1; i >= pos; i--) {
            this.elem[i + 1] = this.elem[i];
        }
        this.elem[pos] = data;
        this.usedSize++;
    }

    public boolean contains(int toFind) {
        // 判定是否包含某个元素
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    public int indexOf(int toFind) {
        // 查找某个元素对应的位置
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    public int get(int pos) {
        // 获取 pos 位置的元素
        if (pos < 0 || pos >= this.usedSize) {
            throw new PosOutOfBoundsException(pos + "位置不合法！");
        }
        return this.elem[pos];
    }

    public void set(int pos, int value) {
        // 给 pos 位置的元素设为 value
        if (pos < 0 || pos >= this.usedSize) {
            throw new PosOutOfBoundsException(pos + "位置不合法！");
        }
        this.elem[pos] = value;
    }

    public void remove(int toRemove) {
        //删除第一次出现的关键字key
        if (indexOf(toRemove) == -1) {
            System.out.println("查无此数");
            return;
        }
        for (int i = indexOf(toRemove); i < this.usedSize - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
        this.usedSize--;
    }

    public int size() {
        // 获取顺序表长度
        return this.usedSize;
    }

    public void clear() {
        // 清空顺序表
        //若为引用类型的顺序表，需要依次置空
//        for (int i = 0; i < this.usedSize; i++) {
//            this.elem[i] = null;
//        }
        this.usedSize = 0;
    }

}
